const { ccclass, property } = cc._decorator;

@ccclass
export default class TouchMove extends cc.Component {

    /** 移动的节点 */
    @property({ type: cc.Node, tooltip: '移动的节点' })
    moveNode: cc.Node = null;

    /** 武器节点 */
    @property({ type: cc.Node, tooltip: '武器节点' })
    wopenNode: cc.Node = null;

    /** 触摸点 */
    @property({ type: cc.Label, tooltip: '触摸点' })
    touchPoint: cc.Label = null;

    /** 在移动状态 */
    isMoving: boolean = false;

    /** 移动到的坐标点 */
    moveToPos: cc.Vec2 = cc.v2(0, 0);

    /** 速率 */
    followSpeed: number = 200;

    start() {
        this.addEmitEvent();
    }

    onTouchStart(event: cc.Event.EventTouch) {
        let touches: cc.Touch[] = event.getTouches();
        let touchLoc = touches[0].getLocation();
        this.isMoving = true;
        this.moveToPos = this.moveNode.parent.convertToNodeSpaceAR(touchLoc);
        this.touchPoint.string = `触摸点 ${touchLoc}`;
    }

    onTouchMove(event: cc.Event.EventTouch) {
        let touches: cc.Touch[] = event.getTouches();
        let touchLoc = touches[0].getLocation();

        this.moveToPos = this.moveNode.parent.convertToNodeSpaceAR(touchLoc);
        this.touchPoint.string = `触摸点 ${touchLoc}`;
    }

    onTouchCanEnd(event: cc.Event.EventTouch) {
        this.isMoving = false;
    }

    update(dt: number) {
        if (!this.isMoving) { return; }
        // cc.log('dt = 0.01 - 0.03');

        let oldPos = new cc.Vec2(this.moveNode.position.x, this.moveNode.position.y);
        // 归一化 计算朝向？
        let direction = this.moveToPos.sub(oldPos).normalize();
        cc.log('direction', direction.x, direction.y);

        // TODO
        let targetPos = new cc.Vec2(this.moveNode.position.x, this.moveNode.position.y);
        let wopensPos = new cc.Vec2(this.wopenNode.position.x, this.wopenNode.position.y);

        let dir = targetPos.sub(wopensPos).normalize();
        this.wopenNode.setPosition(wopensPos.add(dir.mul((this.followSpeed + 10) * dt)));
        this.wopenNode.angle = cc.v2(0, 1).signAngle(dir) * 180 / Math.PI;

        let newPos = oldPos.add(direction.mul(this.followSpeed * dt));
        this.moveNode.setPosition(newPos);
    }

    addEmitEvent() {
        this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart.bind(this), this.node, true);
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove.bind(this), this.node, true);
        this.node.on(cc.Node.EventType.TOUCH_END, this.onTouchCanEnd, this, true);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchCanEnd, this, true);
    }
}